﻿/*
 * @author Lee 
 * Time: 20180403 
 * Abstract: SharePoint API的二次封装
 */

using System;
using System.Collections.Generic;
using Microsoft.SharePoint;

namespace SharePointHelper.DLL.SSOM
{
	public class Event
	{
        #region 获取某个list下最近添加或修改的item
        /// <summary>
        /// 获取某个list下最近添加或修改的item
        /// </summary>
        /// <param name="web"></param>
        /// <param name="listsToInclude"></param>
        /// <param name="listsToExclude"></param>
        /// <param name="itemMinimumDate"></param>
        /// <returns></returns>
        public static List<SPListItem> GetUpcomingEvents(SPList list, bool isIncludeItemsStartedButNotEndedYet)
		{
			string currentEventListUrl = null;
			string currentItemUrl = null;
			List<SPListItem> items = null;
			try
			{
				// 初始化
				if (list == null) { throw new Exception("SPListItem passed is null"); }
				items = new List<SPListItem>();
				currentEventListUrl = list.DefaultViewUrl;


				// 获取 list items
				foreach (SPListItem item in list.Items)
				{
					currentItemUrl = item.Url;
					if (isIncludeItem(item, isIncludeItemsStartedButNotEndedYet)) { items.Add(item); }
					currentItemUrl = null;
				}

				// 获取 list folders
				if (list.Folders != null)
				{
					foreach (SPListItem folder in list.Folders)
					{
						currentItemUrl = folder.Url;
						if (isIncludeItem(folder, isIncludeItemsStartedButNotEndedYet)) { items.Add(folder); }
						currentItemUrl = null;
					}
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("r6ey7yfdhtddrssGsrdrtyfud", ex,
					"current list: " + currentEventListUrl + ", current item: " + currentItemUrl);
				items = null;
			}
			return items;
		}
        #endregion

        #region 从所有event/task type 列表中获取所有即将发生的event
        /// <summary>
        /// 从所有event/task type 列表中获取所有即将发生的event
        /// </summary>
        /// <param name="web"></param>
        /// <param name="isIncludeItemsStartedButNotEndedYet"></param>
        /// <param name="isIncludeTaskLists"></param>
        /// <returns></returns>
        public static List<SPListItem> GetUpcomingEvents(SPWeb web, bool isIncludeItemsStartedButNotEndedYet, bool isIncludeTaskLists)
		{
			List<SPListItem> items = null;
			try
			{
				// 初始化
				if (web == null) { throw new Exception("SPWeb passed is null"); }
				items = new List<SPListItem>();

				foreach (SPList list in web.Lists)
				{
					// 判断是否包含这个list
					bool isIncludeList = false;
					if (list.BaseTemplate == SPListTemplateType.Events) 
					{ 
						isIncludeList = true; 
					}
					else if (isIncludeTaskLists &&
						(list.BaseTemplate == SPListTemplateType.Tasks ||
						list.BaseTemplate == SPListTemplateType.GanttTasks ||
						list.BaseTemplate == SPListTemplateType.IssueTracking)
						)
					{
						isIncludeList = true;
					}

					// 包含这个list
					if (isIncludeList)
					{
						List<SPListItem> _items = GetUpcomingEvents(list, isIncludeItemsStartedButNotEndedYet);
						if (_items != null && _items.Count > 0) { items.AddRange(_items); }
					}
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("fxgjcjyftdrr", ex);
				items = null;
			}
			return items;
		}
        #endregion

        #region 用于判断，是否包含这个item
        //判断是否包含这个item
        private static bool isIncludeItem(SPListItem item, bool isIncludeItemsStartedButNotEndedYet)
		{
			bool _isIncludeItem = false;
			if (item != null)
			{
				string contentTypeName = ContentType.GetContentTypeName(item);
				if (!string.IsNullOrEmpty(contentTypeName))
				{
					DateTime? startDate = null;
					DateTime? endDate = null;
					DateTime? devNull = null;
					GetDatesFromItem(item, ref startDate, ref endDate, ref devNull);

					// date filter
					_isIncludeItem = false;
					if (startDate != null)
					{
						if (startDate.Value.Date >= DateTime.Now.Date)
						{
							if (endDate != null && endDate.Value.Date == DateTime.Now.Date && endDate.Value.AddHours(1) < DateTime.Now)
							{
                                // 比如：会议是今天，但已经结束一个多小时了。
                                _isIncludeItem = false;
							}
							else
							{
                                // item 的开始日期是今天或以后
                                _isIncludeItem = true;
							}
						}
						else if (isIncludeItemsStartedButNotEndedYet && endDate != null && endDate.Value.Date >= DateTime.Now.Date)
						{
                            // item 已经开始了，但还没有结束
                            _isIncludeItem = true;
						}
					}
					else if (endDate != null && endDate.Value.Date >= DateTime.Now.Date)
					{
                        // 只定义结束日期（例如到期日期），是今天或以后
                        _isIncludeItem = true;
					}
				}
			}
			return _isIncludeItem;
		}
        #endregion

        #region 获取关于一个certain content type的 item date  , 比如 event, task, issue, etc.
        /// <summary>
        /// 获取关于一个certain content type的 item date  , 比如 event, task, issue, etc.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="date"></param>
        public static void GetDatesFromItem(SPListItem item, ref DateTime? startDate, ref DateTime? endDate, ref DateTime? date)
		{
			// init
			startDate = null;
			endDate = null;
			date = null;

			if (item != null)
			{
				string contentTypeName = ContentType.GetContentTypeName(item);
				if (!string.IsNullOrEmpty(contentTypeName))
				{
					if (contentTypeName == "Event")
					{
						try
						{
							startDate = item["EventDate"] as DateTime?;
							endDate = item["EndDate"] as DateTime?;
						}
						catch { }
					}
					else if (contentTypeName == "Task" || contentTypeName == "Project Task")
					{
						try
						{
							startDate = item["StartDate"] as DateTime?;
							endDate = item["DueDate"] as DateTime?;
						}
						catch { }
					}
					else if (contentTypeName == "Issue")
					{
						try
						{
							endDate = item["DueDate"] as DateTime?;
						}
						catch { }
					}
				}

				// determine overall date
				if (startDate != null) { date = startDate; }
				else if (endDate != null) { date = endDate; }
			}
		}
        #endregion
    }
}
